#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 序列上索引值迭代
问题: 你想在迭代一个序列的同时跟踪正在被处理的元素索引。
提示 : 
"""

from collections import defaultdict


def recipe1():
    my_list = ['a', 'b', 'c']
    for idx, val in enumerate(my_list):
        print(f"{idx, val = }")

    for idx, val in enumerate(my_list, 1):
        print(f"{idx, val = }")

def recipe2():
    parse_data('10_iterate_index.txt')

def recipe3():
    """将一个文件中出现的单词映射到它出现的行号上去"""
    word_summary = defaultdict(list)
    with open('../somefile.txt', 'r') as f:
        lines = f.readlines()
    
    for idx, line in enumerate(lines):
        # create a list of words in current line
        words = [w.strip().lower() for w in line.split()]
        for word in words:
            word_summary[word].append(idx)
    print(f"{word_summary = }")

def recipe4():
    """已经解压后的元组序列上使用 enumerate() 函数时很容易调入陷阱"""
    data = [ (1, 2), (3, 4), (5, 6), (7, 8) ]
    # for n, x, y in enumerate(data): # Error
    for n, (x, y) in enumerate(data):
        print(f"{n, x, y = }")

    for n, d in enumerate(data):
        print(f"{n, d = }")

def parse_data(filename):
    """遍历文件时想在错误消息中使用行号定位"""
    with open(filename, 'rt') as f:
        for lineno, line in enumerate(f, 1):
            fields = line.split()
            try:
                int(fields[1])
            except ValueError as e:
                print('Line {}: Parse error: {}'.format(lineno, e))  

def main():
    print('recipe1'.center(20, '*'))
    recipe1() 
    print('recipe2'.center(20, '*'))
    recipe2() 
    print('recipe3'.center(20, '*'))
    recipe3() 
    print('recipe4'.center(20, '*'))
    recipe4() 

if __name__ == '__main__':
    main()         